# -*- coding: utf-8 -*-
# Author: xiantingDeng
# File: log_util.py
# Time: 18:28

import os
import time
import logging
from common.utils.file_util import get_log_dir


def console_logger(level=logging.DEBUG):
    '''
    将信息打印到控制台
    :param level: 日志级别，默认DEBUG级别
    :return:logger对象
    '''
    logger = logging.getLogger(__name__)
    logger.setLevel(level=level)
    formatter = logging.Formatter(
        "%(asctime)s %(levelname)s - %(message)s")
    #  file: %(filename)s line: %(lineno)d - %(funcName)s - %(name)s -
    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    console.setFormatter(formatter)
    logger.addHandler(console)
    return logger


def file_logger(log_path=None, level=logging.DEBUG):
    '''
    将信息写入到日志文件
    :param log_path:日志文件绝对路径，不传时在log目录下根据日期格式自动生成
    :param level: 日志级别，默认DEBUG级别
    :return:logger对象
    '''
    logger = logging.getLogger(__name__)
    logger.setLevel(level=level)
    formatter = logging.Formatter(
        "%(asctime)s  %(levelname)s - %(message)s")
    # file: %(filename)s line: %(lineno)d - %(funcName)s - %(name)s -

    if not log_path:
        file_name = "{}.txt".format(time.strftime('%Y-%m-%d_%H_%M', time.localtime()))
        log_path = os.path.join(get_log_dir(), file_name)

    handler = logging.FileHandler(log_path, encoding="utf-8")
    handler.setLevel(level=level)
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    return logger


def file_path():
    file_name = "{}.log.txt".format(time.strftime('%Y-%m-%d_%H_%M', time.localtime()))
    log_path = os.path.join(get_log_dir(), file_name)
    return log_path


def logger(log_path=None, level=logging.DEBUG):
    '''
    将信息打印到控制台并写入文件
    :param log_path: 日志文件绝对路径
    :param level: 日志级别，默认DEBUG级别
    :return: logger对象
    '''
    logger = logging.getLogger(__name__)
    logger.setLevel(level=level)
    formatter = logging.Formatter(
            '[%(asctime)s][%(filename)s %(lineno)d][%(levelname)s]: %(message)s')
    # file: %(filename)s line: %(lineno)d - %(funcName)s - %(name)s -

    if not log_path:
        file_name = "{}.txt".format(time.strftime('%Y-%m-%d_%H_%M', time.localtime()))
        log_path = os.path.join(get_log_dir(), file_name)

    if os.path.exists(log_path):
        file_name = "{}.txt".format(time.strftime('%Y-%m-%d_%H_%M+1', time.localtime()))
        log_path = os.path.join(get_log_dir(), file_name)

    # 日志打印到文件
    handler = logging.FileHandler(log_path, encoding="utf-8")
    handler.setLevel(level=level)
    handler.setFormatter(formatter)

    # 日志打印到控制台
    console = logging.StreamHandler()
    console.setLevel(level=level)
    console.setFormatter(formatter)

    # 添加日志打印到文件和控制台
    logger.addHandler(handler)
    logger.addHandler(console)
    return logger

